from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import generics
from .models import User, Address
from . import serializers
from django.contrib.auth.backends import ModelBackend
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import ModelViewSet
from . import constants


class UsernameCountView(APIView):
    '''
    查询用户名是否存在
    select count(*) from 表名 where username=***
    '''

    def get(self, request, username):
        # 统计用户名个数
        count = User.objects.filter(username=username).count()
        # 响应
        return Response({
            'username': username,
            'count': count
        })


class MobileCountView(APIView):
    '''
    查询手机号是否存在
    '''

    def get(self, request, mobile):
        # 统计手机号个数
        count = User.objects.filter(mobile=mobile).count()
        # 响应
        return Response({
            'mobile': mobile,
            'count': count
        })


class RegisterView(generics.CreateAPIView):
    '''
    注册：创建新用户对象
    '''
    # 指定查询集:当前只实现创建功能，不需要查询，可以不指定
    # 指定序列化器：验证接收的数据，创建
    serializer_class = serializers.UserRegisterSerializer


class UserView(generics.RetrieveAPIView):
    # 需要登录
    permission_classes = [IsAuthenticated]

    serializer_class = serializers.UserSerializer

    # 不需要查询，而是获取当前登录的用户
    # queryset = User.objects.all().get(pk=)
    # 重写方法，不根据主键查询，而是从jwt中获取当前用户
    def get_object(self):
        return self.request.user


class EmailView(generics.UpdateAPIView):
    # 默认修改的逻辑：根据主键查询对象，再修改对象的属性，保存
    # queryset =
    serializer_class = serializers.UserEmailSerializer

    # 访问此视图时，必须先登录
    permission_classes = [IsAuthenticated]

    # 获取当前登录的用户对象，而不是根据主键查询
    def get_object(self):
        return self.request.user


class EmailActiveView(APIView):
    def get(self, request):
        # 1.接收加密信息
        token = request.query_params.get('token')

        # 2.解密验证
        user = User.email_loads(token)
        if user is None:
            return Response({'message': '激活链接无效'})
        # 3.查询用户对象，修改属性
        user.email_active = True
        user.save()

        # 4.响应
        return Response({'message': '激活成功'})


class AddressViewSet(ModelViewSet):
    permission_classes = [IsAuthenticated]

    # queryset = Address.objects.all()
    # 查询当前登录用户的收货地址
    def get_queryset(self):
        # 获取当前登录的用户
        user = self.request.user
        # 获取这个用户的所有收货地址
        return user.addresses.filter(is_deleted=False)

    serializer_class = serializers.AddressSerializer

    def list(self, request, *args, **kwargs):
        user = request.user

        address_list = self.get_queryset()

        serializer = serializers.AddressSerializer(address_list, many=True)

        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data
        })

    def destroy(self, request, *args, **kwargs):
        # 逻辑删除
        address = self.get_object()
        address.is_deleted = True
        address.save()
        return Response(status=204)

    #定义一个新方法
    @action(method = ['put'],detail = True)
    def title(self,request,pk):
        #查询标题
        #1 查询收货地址对象
        try:
            address = Address.object.get(pk =pk )
        except:
            return Response({'message':'编号无效'})

        #2接受收货地址
        title_dict = request.data

        #验证 修改
        serializer =serializers.TitleSerializer
        serializer.is_valid(raise_exception=True)
        address = serializers.save()

        #响应
        return Response({
            'id':address.id,
            'title':address.title

        })

    @action(method = ['put'],detail = True)
    def status(self,request,pk):
        #设置默认收货地址
        user = request.user
        user.default_address = pk
        user.save()
        return Response({'msg':'OK'})